#! /usr/bin/python
# encoding=utf-8
# Created by Fenglu Niu on 2025/2/28 21:51
import signal

import gevent
from gevent import monkey, pywsgi

monkey.patch_all()

import common
import searcher

from flask import Flask, request


def signal_handler():
    common.get_logger().info('手动终止程序')
    server.stop(timeout=5)
    common.get_logger().info('flask服务已关闭')


gevent.signal_handler(signal.SIGINT, signal_handler)
gevent.signal_handler(signal.SIGTERM, signal_handler)

app = Flask(__name__)
app.logger.disabled = True


def load_config():
    app.config.from_pyfile('config/config.py', silent=True)


load_config()


@app.route('/search', methods=['POST'])
def deep_search():
    body = request.get_json()
    engine = body.get('engine', app.config.get('DEFAULT_SEARCH_ENGINE'))
    cookie = body.get('cookie')
    user_agent = body.get('user_agent', app.config.get('DEFAULT_USER_AGENT'))
    keyword = body.get('keyword')
    num = body.get('num', 10)
    common.get_logger().info('收到请求：引擎：%s，关键词：%s，数量：%s' % (engine, keyword, num))
    resp = searcher.Context.do_search(engine, keyword, cookie, user_agent, num)
    return resp


@app.route('/reload_config', methods=['GET'])
def reload_config():
    load_config()
    common.get_logger().info('Configuration reloaded!')
    return 'Configuration reloaded!'


if __name__ == '__main__':
    server = pywsgi.WSGIServer(('0.0.0.0', 28257), app, log=None)
    common.get_logger().info('深度搜索服务已启动，监听端口28257')
    server.serve_forever()
